package young.elasticjob.lite;

import org.apache.shardingsphere.elasticjob.api.JobConfiguration;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.infra.env.IpUtils;
import org.apache.shardingsphere.elasticjob.lite.api.bootstrap.impl.ScheduleJobBootstrap;
import org.apache.shardingsphere.elasticjob.reg.base.CoordinatorRegistryCenter;
import org.apache.shardingsphere.elasticjob.reg.zookeeper.ZookeeperConfiguration;
import org.apache.shardingsphere.elasticjob.reg.zookeeper.ZookeeperRegistryCenter;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;

/**
 * 简单类型作业-测试
 * elasticjob-lite-core版本3.0.0-RC1
 * Zookeeper版本3.6.3（3.6.+）
 *
 * @author ：<a href="mailto:youngkun2016@163.com">young</a>
 * @date ：Created in 2021/5/11
 */
public class ElasticJobTest {
    public static void main(String[] args) {
        new ScheduleJobBootstrap(createRegistryCenter(), new MyJob(), createJobConfiguration()).schedule();
    }

    private static CoordinatorRegistryCenter createRegistryCenter() {
        //应对本地测试ip is null异常
        IpUtils.setIp("192.168.3.35");
        CoordinatorRegistryCenter regCenter = new ZookeeperRegistryCenter(new ZookeeperConfiguration("127.0.0.1:2181", "my-job"));
        regCenter.init();
        return regCenter;
    }

    private static JobConfiguration createJobConfiguration() {        // 创建作业配置
        JobConfiguration jobConfig = JobConfiguration.newBuilder("MyJob", 3).cron("0/5 * * * * ?").build();
        return jobConfig;
    }

    public static class MyJob implements SimpleJob {
        @Override
        public void execute(ShardingContext context) {
            switch (context.getShardingItem()) {
                case 0:
                    // do something by sharding item 0
                    System.out.println("do something by sharding item 0");
                    break;
                case 1:
                    // do something by sharding item 1
                    System.out.println("do something by sharding item 1");
                    break;
                case 2:
                    // do something by sharding item 2
                    System.out.println("do something by sharding item 2");
                    break;
                // case n: ...
                default:
                    System.out.println("do something by sharding item default");
                    break;
            }
        }
    }
}
